package com.ormlite.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.ormlite.pojo.Event;
import com.ormlite.pojo.Movie;

public class OrmLiteHelper extends OrmLiteSqliteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "ormLiteAndroid.db";

	private static OrmLiteHelper instance = null;
	private RuntimeExceptionDao<Movie, Integer> movieRuntimeDao = null;
	private RuntimeExceptionDao<Event, Integer> eventRuntimeDao = null;

	public OrmLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		if (instance == null) {
			synchronized (OrmLiteHelper.class) {
				OrmLiteHelper inst = instance;
				if (inst == null) {
					synchronized (OrmLiteHelper.class) {
						instance = this;
					}
				}
			}
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
		try {
			TableUtils.createTableIfNotExists(connectionSource, Movie.class);
			TableUtils.createTableIfNotExists(connectionSource, Event.class);
		} catch (SQLException e) {
			Log.e(OrmLiteHelper.class.getName(), "Can't create tables", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		Log.i(OrmLiteHelper.class.getName(), "onUpgrade");
	}

	@Override
	public void close() {
		super.close();
		movieRuntimeDao = null;
		eventRuntimeDao = null;
	}

	public static RuntimeExceptionDao<Movie, Integer> getMovieRuntimeDao() {
		if (instance.movieRuntimeDao == null) {
			instance.movieRuntimeDao = instance.getRuntimeExceptionDao(Movie.class);
		}
		return instance.movieRuntimeDao;
	}

	public static RuntimeExceptionDao<Event, Integer> getEventRuntimeDao() {
		if (instance.eventRuntimeDao == null) {
			instance.eventRuntimeDao = instance.getRuntimeExceptionDao(Event.class);
		}
		return instance.eventRuntimeDao;
	}
}
